package me.cxlr.qinlauncher2.view.settings;

import android.os.Bundle;

import androidx.appcompat.app.AlertDialog;
import androidx.preference.DropDownPreference;
import androidx.preference.PreferenceFragmentCompat;
import androidx.preference.SwitchPreferenceCompat;

import java.util.ArrayList;
import java.util.List;

import me.cxlr.qinlauncher2.R;
import me.cxlr.qinlauncher2.constants.Constants;
import me.cxlr.qinlauncher2.constants.LauncherAction;
import me.cxlr.qinlauncher2.dao.ActionDao;
import me.cxlr.qinlauncher2.dao.AppDao;
import me.cxlr.qinlauncher2.dao.KeyActionDao;
import me.cxlr.qinlauncher2.model.Action;
import me.cxlr.qinlauncher2.model.App;
import me.cxlr.qinlauncher2.model.AppAndAction;
import me.cxlr.qinlauncher2.model.KeyAction;
import me.cxlr.qinlauncher2.util.ResourceUtil;
import me.cxlr.qinlauncher2.util.SharedPreferencesUtil;
import me.cxlr.qinlauncher2.util.ThemeUtil;

/**
 * @author 酷安用户:山轮纸
 */
public class DpadKeySettingsFragment extends PreferenceFragmentCompat {
    private AppDao appDao;
    private ActionDao actionDao;
    private KeyActionDao keyActionDao;
    private boolean useDpadKeyFlag;

    private SwitchPreferenceCompat useDpadKey;
    private DropDownPreference ddpKeyDpadKeyUp;
    private DropDownPreference ddpKeyDpadKeyDown;
    private DropDownPreference ddpKeyDpadKeyLeft;
    private DropDownPreference ddpKeyDpadKeyRight;

    @Override
    public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
        setPreferencesFromResource(R.xml.preferences_dpad_key_settings, rootKey);

        useDpadKey = findPreference("use_dpad_key");
        ddpKeyDpadKeyUp = findPreference("dpad_key_up");
        ddpKeyDpadKeyDown = findPreference("dpad_key_down");
        ddpKeyDpadKeyLeft = findPreference("dpad_key_left");
        ddpKeyDpadKeyRight = findPreference("dpad_key_right");

        appDao = new AppDao();
        actionDao = new ActionDao();
        keyActionDao = new KeyActionDao();

        List<KeyAction> keyActionList = keyActionDao.findKeyActionListByKeyType(3);
        for (KeyAction keyAction : keyActionList) {
            switch (keyAction.getKeyName()) {
                case Constants.DPAD_KEY_UP:
                    initDpadKeyDropDownPreferenceSelect(getString(R.string.dpad_key_up_title), ddpKeyDpadKeyUp, keyAction);
                    break;
                case Constants.DPAD_KEY_DOWN:
                    initDpadKeyDropDownPreferenceSelect(getString(R.string.dpad_key_down_title), ddpKeyDpadKeyDown, keyAction);
                    break;
                case Constants.DPAD_KEY_LEFT:
                    initDpadKeyDropDownPreferenceSelect(getString(R.string.dpad_key_left_title), ddpKeyDpadKeyLeft, keyAction);
                    break;
                case Constants.DPAD_KEY_RIGHT:
                    initDpadKeyDropDownPreferenceSelect(getString(R.string.dpad_key_right_title), ddpKeyDpadKeyRight, keyAction);
                    break;
                default:
                    break;
            }

        }

        useDpadKeyFlag = SharedPreferencesUtil.getInstance().getBoolean("use_dpad_key", false);
        setNumberKeySelectEnabled(useDpadKeyFlag);

        assert useDpadKey != null;
        useDpadKey.setOnPreferenceChangeListener((preference, newValue) -> {
            useDpadKeyFlag = Boolean.parseBoolean(newValue.toString());
            setNumberKeySelectEnabled(useDpadKeyFlag);
            return true;
        });

    }

    @Override
    public void onResume() {
        super.onResume();
        ThemeUtil.initTheme();
    }

    /**
     * 设置选择方向键对应功能的按钮是否可点击
     *
     * @param useDpadKeyFlag 是否使用方向键功能
     */
    private void setNumberKeySelectEnabled(boolean useDpadKeyFlag) {
        if (useDpadKeyFlag) {
            ddpKeyDpadKeyUp.setEnabled(true);
            ddpKeyDpadKeyDown.setEnabled(true);
            ddpKeyDpadKeyLeft.setEnabled(true);
            ddpKeyDpadKeyRight.setEnabled(true);
        } else {
            ddpKeyDpadKeyUp.setEnabled(false);
            ddpKeyDpadKeyDown.setEnabled(false);
            ddpKeyDpadKeyLeft.setEnabled(false);
            ddpKeyDpadKeyRight.setEnabled(false);
        }
    }

    /**
     * init DropDownPreference
     *
     * @param title              方向按键名称，用作dialog的Title
     * @param dropDownPreference DropDownPreference
     * @param keyAction          KeyAction
     */
    private void initDpadKeyDropDownPreferenceSelect(String title, DropDownPreference dropDownPreference, KeyAction keyAction) {
        switch (keyAction.getActionType()) {
            case 1:
                dropDownPreference.setSummary(getString(R.string.number_key_select_open_app_summary, keyAction.getApp().getLabel()));
                break;
            case 2:
                String label = ResourceUtil.getString(requireActivity(), keyAction.getAction().getResLabel());
                dropDownPreference.setSummary(getString(R.string.number_key_select_action_summary, label));
                break;
            case 0:
                dropDownPreference.setSummary(getString(R.string.dpad_key_no_select_summary));
                break;
            default:
                break;
        }
        dropDownPreference.setOnPreferenceClickListener(view -> {
            dialogChoice("选择" + title, keyAction, dropDownPreference);
            return true;
        });
    }

    /**
     * 选择动作或应用
     *
     * @param title title
     */
    private void dialogChoice(String title, KeyAction keyAction, DropDownPreference dropDownPreference) {
        ArrayList<AppAndAction> appAndActionList = new ArrayList<>(16);
        List<Action> actionList = actionDao.findAllAction();
        if (actionList != null) {
            for (Action entity : actionList) {
                String label = ResourceUtil.getString(requireActivity(), entity.getResLabel());
                if (entity.getActionName().equals(LauncherAction.NO.getAction())){
                    appAndActionList.add(AppAndAction.builder().id(entity.getId()).label(label).type(0).build());
                }else{
                    appAndActionList.add(AppAndAction.builder().id(entity.getId()).label(label).type(2).build());
                }
            }
        }
        List<App> appList = appDao.findAllApp();
        if (appList != null) {
            for (App entity : appList) {
                appAndActionList.add(AppAndAction.builder().id(entity.getId()).label(entity.getLabel()).type(1).build());
            }
        }

        String[] id = new String[appAndActionList.size()];
        String[] label = new String[appAndActionList.size()];
        int[] type = new int[appAndActionList.size()];
        for (int i = 0; i < appAndActionList.size(); i++) {
            id[i] = appAndActionList.get(i).getId();
            label[i] = appAndActionList.get(i).getLabel();
            type[i] = appAndActionList.get(i).getType();
        }

        AlertDialog alertDialog = new AlertDialog.Builder(requireContext())
                .setTitle(title)
                .setItems(label, (dialog, which) -> {
                    updateDpadKeyAction(keyAction, dropDownPreference, id[which], type[which]);
                    dialog.dismiss();
                })
                .setPositiveButton("关闭", (dialog, which) -> dialog.dismiss())
                .create();
        alertDialog.show();
    }

    /**
     * 修改方向键动作
     *
     * @param keyAction          方向键动作
     * @param dropDownPreference DropDownPreference
     * @param id                 被选中的id
     * @param type               主键的类型 1是app 2是动作
     */
    private void updateDpadKeyAction(KeyAction keyAction, DropDownPreference dropDownPreference, String id, int type) {
        if (type == Constants.KEY_ACTION_TYPE_OPEN_APP) {
            App app = appDao.findAppById(id);
            keyAction.setActionType(1);
            keyAction.setAction(null);
            keyAction.setApp(app);
        } else if (type == Constants.KEY_ACTION_TYPE_ACTION) {
            Action action = actionDao.findActionById(id);
            keyAction.setActionType(2);
            keyAction.setAction(action);
            keyAction.setApp(null);
        } else if (type == Constants.KEY_ACTION_TYPE_NO) {
            keyAction.setActionType(0);
            keyAction.setAction(null);
            keyAction.setApp(null);
        }
        keyActionDao.updateKeyAction(keyAction);
        switch (keyAction.getActionType()) {
            case 1:
                dropDownPreference.setSummary(getString(R.string.number_key_select_open_app_summary, keyAction.getApp().getLabel()));
                break;
            case 2:
                String label = ResourceUtil.getString(requireActivity(), keyAction.getAction().getResLabel());
                dropDownPreference.setSummary(getString(R.string.number_key_select_action_summary, label));
                break;
            case 0:
                dropDownPreference.setSummary(getString(R.string.dpad_key_no_select_summary));
                break;
            default:
                break;
        }
    }
}